var functions = {
  /**
   * @name 判断传入地址的图片是否加载成功
   * @param {str} imgurl 
   * @param {function} callback 
   */
  imgLoad(imgurl, callback) {
    var img = new Image()
    img.src = imgurl
    if (callback) {
      callback()
    }
    return img.complete
  },

  /**
   * @name 倒计时
   * @param {int} time 
   * @param {function} callback
   */
  countDown(time, callback) {
    var timeDown = setInterval(() => {
      // return time
      if (time == 0) {
        clearInterval(timeDown)
        if (callback) callback()
      } else {
        time--
      }
    }, 1000)
  },

  /**
   * @name 获取当前路由path
   * @param {*} vue 
   */
  getRouterPath(vue) {
    var routerPath = vue.$router.history.current.path
    return routerPath
  },

  /**
   * @name 获取当前路由中携带的参数，返回param或者返回全部的参数
   * @param {*} vue 
   * @param {str} param 
   */
  getRouterParams(vue, param) {
    if (param) {
      return vue.$router.history.current.params.param
    } else {
      return vue.$router.history.current.params
    }
  },

  getBacImg(vue) {
    return 'background:url(' + localStorage.getItem("homepageImg") + ');background-position-x:' + vue.$store.state.homePageBac.positionX + ';background-position-y:' + vue.$store.state.homePageBac.positionY + ';background-size:' + vue.$store.state.homePageBac.bacSize
  },

  /**
   * @name 从array中获取符合的obj
   */
  getRightItem(array, key, value) {
    for (var item of array) {
      if (item[key] == value) {
        return item
      }
    }
  },

  /**
   * @name 信息提示窗口
   * @param {*} res 
   * @param {function} callback 回调函数 
   */
  toMessage(res,callback) {
    if(!res)return
    window._bus.$message({
      type: res.status == 0 ? "success" : "error",
      message: res.msg|| res.data
    })
    if(res.status==0&&callback){
      callback()
    }
  },

  /**
   * @name 调用方法序列
   * @param {*} array 
   */
  async orderMethods(array = []) {
    for (var i = 0; i < array.length; i++) {
      await array[i]()
    }
  },

  /**
   * @name 检查参数
   * @param {*} model 数据模板
   * @param {*} params 检查的数据
   */
  checkParams(model,params){
    if(!model)throw new Error('数据模板不能为空')
    if(!params)throw new Error('检查的数据不能为空')
    for(var i=0;i<model.length;i++){
      if(model[i].checked&&!params[model[i].prop]){
        _g.toMessage({status:1,msg:model[i].label+"不能为空"})
        return true
      }
    }
    return false
  },

  /**
   * @name apiPost 封装post方法
   * @param {*} url 
   * @param {*} data 
   */
  async apiPost(url, data,useCheck) {
    var path = PATH + url
    var result = null
    
    if(useCheck){
      if(! await _g.autoTestFormal(data)){
        return undefined
      }
    }
    
    try {
      await _axios.post(path, qs.stringify(data)).then(res => {
        result = res
        if(res.data.status==10){
          _g.toMessage({ type: "warning", msg:"请重新登录" })
          setTimeout(()=>{location.href="/login"},520)
        }
      });
    }
    catch (err) {
      var message = "出问题了"
      switch (err.toString().split(" ").slice(-1)[0]) {
        case "404": message = "访问地址不正确"; break;
        case "500": message = "后台出错"; break;
      }
      _g.toMessage({ type: "warning", msg:message })
    }
    return await result ? result.data : null;
  },

  /**
   * @name 自动验证输入格式
   */
  autoTestFormal(params={}){
    var rules = new Map([
      ['phone',{label:"手机号",exp:/^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/}],
      ['password',{label:"密码",exp:/.{6,18}/}],
      ['yards',{label:"验证码",exp:/.{6}/}],
      ['idno',{label:"身份证",exp:/^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/}],
    ])

    for(var key in params){
      let ruleinfo = rules.get(key)
      if(ruleinfo&&!ruleinfo.exp.test(params[key])){
        _g.toMessage({ type: "warning", msg:ruleinfo.label+"格式不正确" })
        return false
      }
    }
    return true
  },


  /**
   * @name 生成[num]的数组
   * @param {*} num 
   */
  getNumArray(num) {
    return new Array(num).fill("").map((val, index) => (index + 1))
  },

  // 全屏
  /**
   * @name 全屏显示局部元素
   * @param {*} id 
   * @param {*} vue 
   * @param {function} callback
   */
  fullScreen(id,vue,callback) {
    if(!id)throw new Error("全屏元素的id必填")

    let fullarea = document.getElementById(id);
    
    if (vue.isFullScreen) {
      // 退出全屏
      if (document.exitFullscreen) {
        document.exitFullscreen();
      } else if (document.webkitCancelFullScreen) {
        document.webkitCancelFullScreen();
      } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen();
      } else if (document.msExitFullscreen) {
        document.msExitFullscreen();
      }
    } else {
      // 进入全屏
      if (fullarea.requestFullscreen) {
        fullarea.requestFullscreen();
      } else if (fullarea.webkitRequestFullScreen) {
        fullarea.webkitRequestFullScreen();
      } else if (fullarea.mozRequestFullScreen) {
        fullarea.mozRequestFullScreen();
      } else if (fullarea.msRequestFullscreen) {
        // IE11
        fullarea.msRequestFullscreen();
      }
    }

    if(callback){
      setTimeout(()=>{
        callback()
      },200)
    }
    
    vue.$set(vue,'isFullScreen',!vue.isFullScreen)
  },

  /**
   * @name 单个数字转换为大写
   * @param {*} word 
   */
  toUp(word){
    switch (word) {
      case "0": return "零"
      case "1": return "壹"
      case "2": return "贰"
      case "3": return "叁"
      case "4": return "肆"
      case "5": return "伍"
      case "6": return "陆"
      case "7": return "柒"
      case "8": return "捌"
      case "9": return "玖"
    }
  },

  /**
   * @description 加密
   * @param {str} str
   */
  encrypt(str,type){
    let array=[["身份证",[6,14]]]
    let res = new Map(array).get(type)
    return str.slice(0,res[0])+(new Array(res[1]-res[0]).fill("*").join(""))+str.slice(res[1])
  },


  /**
   * @name 找出所有元素
   * @param {string} string
   */
  findAll(array,string){
    let res = []
    let keyValue = string.split("=")
    let [key,value]=keyValue
    array.forEach(ele=>{
      if(ele[key]==value){
        res.push(ele)
      }
    })
    return res
  },

  /**
   * @name 拓展方法
   * @param {*} name 
   * @param {*} method 
   */
  fn(name, method) {
    if (!method) throw new Error("拓展方法未定义")
    if (Object.keys(this).includes(name)) throw new Error("方法名" + name + "重复")
    this[name] = method
  }
}

export default functions